import React, { Component } from 'react';
import { connect } from 'react-redux';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import fontawesome from '@fortawesome/fontawesome';
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import icons from '@fortawesome/fontawesome-free-solid';
import 'react-datepicker/dist/react-datepicker.css';
import '../resources/styles/Main.css';
import 'moment/locale/zh-cn';

moment.locale('zh-cn');
fontawesome.library.add(icons);
window.moment = moment;

class Main extends Component {
  constructor(props) {
    super(props);
    this.handleSelect = this.handleSelect.bind(this);
    this.handleDeleteOrCancel = this.handleDeleteOrCancel.bind(this);
    this.handleEditOrSave = this.handleEditOrSave.bind(this);
    this.logout = this.logout.bind(this);
  }

  componentWillMount() {
    if (!this.props.authenticated) {
      this.props.history.push('/login');
      return;
    }
    this.props.dispatch({ type: '$profile' });
    this.props.dispatch({
      type: '$query',
      param: {
        selected: this.props.selected
      }
    })
  }

  logout(){
    this.props.dispatch({ type: '$logout' });
  }

  handleSelect(e) {
    this.props.dispatch({
      type: '$query',
      param: {
        selected: e.target.value
      }
    })
  }



  handleChange({date,time,desc},index) {
    this.props.dispatch({
      type: '#formchange',
      payload: {
        index,
        date,
        time,
        desc
      }
    })
  }

  // 添加 编辑 更新
  handleEditOrSave({index,date,time,desc,status}){
    if (!status) {//将记录切换为编辑状态
      this.props.dispatch({
        type: '#edit',
        payload: { index }
      });
      return;
    }

    const { records, selected } = this.props;
  
    const conflictDate = records.some((item, idx) => moment(item.date).format('YYYY-MM-DD') === date && typeof item.status === 'undefined' && idx!=index);
    if (conflictDate && status === 2) { // 新添加的日期不能重复
      alert('亲,加班日期有重复!');
      return;
    }

    if (!time || !/^2[0,1,2,3]:\d{2}$/.test(time)) {
      alert(`第[${index + 1}]条记录打卡时间格式不正确，请设置在【20:00-23:59】区间。`);
      return;
    }

    if(!desc) {
      alert(`第[${index + 1}]条记录未填写加班事由，请简要描述加班原因。`);
      return;
    }

    if (moment(selected).month()!==moment(date).month()){
      alert(`第[${index + 1}]条记录所选的日期与当前选择的月份不一致，请仔细斟酌。`);
      return;
    }

    this.props.dispatch({
      type: status === 2 ? '$create' : '$update', //  2-创建新纪录 1-更新记录
      param: {
        index,
        selected,
        record: { date, time, desc },
      }
    });
  }

  // 取消 删除
  handleDeleteOrCancel(index,status) {
    const { records } = this.props;

    if(status === 1){ // 取消
      this.props.dispatch({
        type: '#cancel',
        payload: { index }
      })
      return;
    }

    if (status === 2) { // 本地删除
      this.props.dispatch({
        type: '#remove',
        payload:{ index }
     })
      return;
    }

    if(!window.confirm('确认删除本条记录？')){
      return;
    }
    // 远端删除
    this.props.dispatch({
      type: '$remove',
      param: {
        index,
        id: records[index]['_id']
      }
    })
  }

  render() {
    return (
      <div className="main">
        <header>
          <div className="logo"></div>
          <div className="user">
          <span className="logout" onClick={this.logout}>退出</span>
          </div>
        </header>
        <div className="sec-hd">
          <h1>加班申报表<small>OVERTIME APPLICATION</small></h1>
        </div>
        <div className="sec-body">
          <div className="page">
            <div className="table-heading">
              <h2>互联网金融部加班申报表</h2>
              <p className="meta-info">
                姓名:<span>{this.props.user.username}</span>
                月份:
                <select onChange={this.handleSelect}>
                  {
                    this.props.options.map((item, idx) => (
                      <option
                        key={idx}
                        value={item.format('YYYY-MM-DD')}>
                        {item.format('YYYY年MM月')}
                      </option>
                    ))
                  }
                </select>
              </p>
            </div>

            <table>
              <thead>
                <tr>
                  <th width="50">序号</th>
                  <th width="130">日期</th>
                  <th width="80">打卡时间</th>
                  <th>加班事项</th>
                  <th width="120">操作</th>
                </tr>
              </thead>
              <tbody>
                {
                  this.props.records.map((record, index) => (
                    <FormItem
                      key={index}
                      index={index}
                      delOrCancel={this.handleDeleteOrCancel}
                      editOrSave={this.handleEditOrSave}
                      {...record}
                    />
                  ))
                }
              </tbody>
            </table>
          </div>
          <div
            className="btn btn-add"
            onClick={() => this.props.dispatch({ type: '#create' })}>
            <FontAwesomeIcon icon='plus-circle' /><span>新增</span>
          </div>
          <div className="tips">
            <strong>提示</strong> 1.新增记录后点击'添加'即可同步数据。2.编辑记录后点击'保存'即可同步数据。
          </div>
        </div>

      </div>
    );
  }
}

class FormItem extends Component {
  constructor(props){
    super(props);
    this.state = {
      index: props.index,
      date: props.date,
      time: props.time,
      desc: props.desc,
      status: props.status
    }
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      index: nextProps.index,
      date: nextProps.date,
      time: nextProps.time,
      desc: nextProps.desc,
      status: nextProps.status
    })
  }
  render() {
    const { index,date,time,desc,status } = this.state;
    return (
      <tr className={status ? 'edit' : ''}>
        <td>
          {index + 1}
        </td>
        <td>
          <DatePicker
            dateFormat="YYYY-MM-DD"
            selected={moment(date)}
            minDate={moment(date).startOf('month')}
            maxDate={moment(date).endOf('month')}
            disabled={!status}
            placeholderText="Select a weekday"
            onChange={date => this.setState({ date: date.format('YYYY-MM-DD') })} />
        </td>
        <td>
          <input
            type="text"
            value={time}
            readOnly={!status}
            placeholder="打卡时间"
            onChange={e => this.setState({ time: e.target.value })} />
        </td>
        <td>
          <input
            type="text"
            value={desc}
            placeholder="加班事由"
            readOnly={!status}
            onChange={e => this.setState({ desc: e.target.value })} />
        </td>
        <td>
          <span className="btn1" onClick={() => this.props.editOrSave(this.state)}>{['编辑', '保存', '添加'][status || 0]}</span>
          <span className="btn2" onClick={() => this.props.delOrCancel(index,status)}>{status === 1 ? '取消' : '删除'}</span>
        </td>
      </tr>
    )
  }
}

function mapStateToProps(state) {
  return {
    ...state.main,
    ...state.auth,
    user: state.user
  }
}

export default connect(mapStateToProps)(Main);
